@file:Suppress("DEPRECATION")

package com.eques.demo.bind

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Intent
import android.location.LocationManager
import android.os.*
import android.text.Html
import android.util.Log
import android.view.View
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.location.LocationManagerCompat
import blufi.espressif.BlufiCallback
import blufi.espressif.BlufiClient
import blufi.espressif.response.BlufiScanResult
import blufi.espressif.response.BlufiStatusResponse
import blufi.espressif.response.BlufiVersionResponse
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONException
import com.eques.base.BaseActivity
import com.eques.bean.WifiConfigResult
import com.eques.bean.WifiListBean
import com.eques.demo.R
import com.eques.event.EventTotalThread
import com.eques.icvss.core.module.user.BuddyType
import com.eques.icvss.utils.ELog
import com.eques.util.Config
import com.eques.util.ObjIsEmptyUtils
import com.eques.util.PermissionInterceptor
import com.eques.view.PopUtils
import com.hjq.permissions.XXPermissions
import org.apache.commons.lang3.StringUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.lang.ref.WeakReference
import java.net.InetAddress
import java.net.UnknownHostException
import java.util.*
import java.util.concurrent.Executors

/**
 * 添加动物设备相关绑定界面
 * 代码待分割
 */
class BindDevActivity : BaseActivity() {

    companion object {
        private var TAG: String = "AnimalDeviceActivity.this"

        private var devRole: Int? = 0

        //是否已经连接蓝牙
        private var isConnectBlue = false

        //设备是否绑定成功
        private var isSetWifiSuccess = false

        //是否已经接收蓝牙返回数据
        private var isReceiveData = false

        //返回网络列表
        private var wifiListBean: MutableList<WifiListBean>? = null

        //当前连接的网络名称
        private var wifiAccount: String? = ""

        //当前连接的网络密码
        private var wifiPass: String? = ""

        //当前登录的用户名
        private var userName: String? = null

        //当前绑定进入的流程位置
        private var bindStepType: Int? = null

        //当前弹出dialog类型
        private var dialogType = 0

        private var HANDLER_SEARCH_BLUE_TIME_OUT = 100//搜索蓝牙超时
        private var HANDLER_SEND_WIFI_TIME_OUT = 101//发送配网信息超时
        private var HANDLER_GET_WIFI_TIME_OUT = 102//发送配网信息超时
        private var REQUEST_ENABLE_BT = 103//发送配网信息超时
    }

    private var BIND_HAS_GET_WIFI: Int? = 1  //已经获取到WIFI,进入网络输入界面
    private var BIND_DEVICE_SUCCESS: Int? = 2  //设备绑定成功

    private var cbHearRing: CheckBox? = null
    private var tvMainLeftTopHint: TextView? = null
    private var tvMainTitleHint: TextView? = null
    private var cst_layout: ConstraintLayout? = null
    private var constraintGlide: ConstraintLayout? = null
    private var btnComfirm: Button? = null
    private var linAddWifi: LinearLayout? = null
    private var tvWifiNeed: TextView? = null
    private var etWifiAccount: EditText? = null
    private var etWifiPwd: EditText? = null
    private var btnWifiDataSave: Button? = null
    private var relBindSuccess: RelativeLayout? = null

    //蓝牙扫描对象
    private var mScanCallback: ScanCallback? = null

    //是否已经连接蓝牙
    private var mBlufiClient: BlufiClient? = null

    //拼接蓝牙返回数据包
    private var stringBuilder = java.lang.StringBuilder()
    var scanner: BluetoothLeScanner? = null

    //蓝牙申请权限
    private val accessCode = 101
    private val permissions: Array<String> = arrayOf(
        Manifest.permission.BLUETOOTH_CONNECT,
        Manifest.permission.BLUETOOTH_SCAN
    )


    private val mHandler = MyHandler(WeakReference(this))

    private class MyHandler(val wrActivity: WeakReference<BindDevActivity>) :
        Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val activity = wrActivity.get()
            when (msg.what) {
                HANDLER_SEARCH_BLUE_TIME_OUT -> {
                    activity?.stopScan()
                    ELog.showToast(
                        activity!!,
                        activity?.getString(R.string.search_wifi_fail),
                        Toast.LENGTH_LONG
                    )
                    activity.finish()
                    activity.stopProgressDialog()
                }

                HANDLER_SEND_WIFI_TIME_OUT -> {
                    ELog.showToast(
                        activity,
                        activity?.getString(R.string.bind_wifi_fail),
                        Toast.LENGTH_LONG
                    )
                    activity?.stopProgressDialog()
                }

                HANDLER_GET_WIFI_TIME_OUT -> {
                    removeMessages(HANDLER_SEARCH_BLUE_TIME_OUT)
                    activity?.scan()
                }
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_animl_device)
        EventBus.getDefault().register(this@BindDevActivity)
        initData()
        initView()

    }


    override fun initView() {
        cbHearRing = findViewById(R.id.cb_hear_ring)
        tvMainLeftTopHint = findViewById(R.id.tv_main_left_top_hint)
        tvMainTitleHint = findViewById(R.id.tv_main_title_hint)
        btnComfirm = findViewById(R.id.btn_comfirm)
        cst_layout = findViewById(R.id.cst_layout)
        linAddWifi = findViewById(R.id.lin_add_wifi)
        tvWifiNeed = findViewById(R.id.tv_wifi_need)
        etWifiAccount = findViewById(R.id.et_wifi_account)
        etWifiPwd = findViewById(R.id.et_wifi_pwd)
        btnWifiDataSave = findViewById(R.id.btn_wifi_data_save)
        constraintGlide = findViewById(R.id.constraint_glide)
        relBindSuccess = findViewById(R.id.rel_bind_success)

        tvWifiNeed?.text = Html.fromHtml(getString(R.string.bind_wifi_need))

        devRole = intent.getIntExtra(Config.ADDING_DEVICES_TYPE, BuddyType.TYPE_WIFI_DOOR_WS2)

        Log.e(TAG, "=======>$devRole")

        initTitleView()

        initListener()

        getIpDetails()

        setWifi()

        judgeDevType()
    }

    override fun initData() {
        userName =preference.getString(Config.EQUES_USER_KEY)
    }

    private fun judgeDevType() {
        if (devRole != BuddyType.TYPE_WIFI_DOOR_WS2 && devRole != BuddyType.TYPE_WIFI_DOOR_WS3) {
            bindStepType = BIND_HAS_GET_WIFI
            showStepView()
            XXPermissions.with(this) //单个权限
                .permission(*Config.PERMISSIONS_LOCATION)
                .interceptor(PermissionInterceptor()) //  .unchecked()
                .request { permissions2: List<String?>?, all2: Boolean ->
                    if (all2) {
                        isConnectBlue = false
                        scan()
                    }
                }
        }
    }

    private fun setWifi() {
        wifiAccount = preference.getString(Config.PERFERS_WIFIACCOUNT, "")
        wifiPass = preference.getString(wifiAccount, wifiPass)
        etWifiAccount?.setText(wifiAccount)
        etWifiPwd?.setText(wifiPass)
    }

    private fun initListener() {
        this.cbHearRing?.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                btnComfirm?.setBackgroundResource(R.drawable.nextstep_btn_shape_selector)
                btnComfirm?.isEnabled = true
            } else {
                btnComfirm?.setBackgroundResource(R.drawable.nextstep_btn_shape_selector_gray)
                btnComfirm?.isEnabled = false
            }
        }
    }

    /**
     * 初始化头部标题栏
     */
    private fun initTitleView() {
        tvMainLeftTopHint!!.visibility = View.VISIBLE
        tvMainLeftTopHint?.setCompoundDrawablesWithIntrinsicBounds(
            resources.getDrawable(R.mipmap.ic_invitation_menu),
            null,
            null,
            null
        )
        tvMainTitleHint!!.visibility = View.VISIBLE
        tvMainTitleHint!!.text = getString(R.string.animal_reset_device)
        tvMainTitleHint!!.setTextColor(resources.getColor(R.color.common_color_333333))
        tvMainLeftTopHint?.setOnClickListener {
            finish()
        }
    }

    @SuppressLint("InvalidR2Usage")
    fun viewClick(view: View) {
        if (view.id == R.id.btn_comfirm) {
            XXPermissions.with(this) //单个权限
                .permission(*Config.PERMISSIONS_LOCATION)
                .interceptor(PermissionInterceptor()) //  .unchecked()
                .request { permissions2: List<String?>?, all2: Boolean ->
                    if (all2) {
                        isConnectBlue = false
                        scan()
                    }
                }

        } else if (view.id == R.id.btn_wifi_data_save) {
            wifiAccount = etWifiAccount?.text.toString()
            if (StringUtils.isEmpty(wifiAccount)) {
                Toast.makeText(this, getString(R.string.bind_wifi_is_null), Toast.LENGTH_SHORT)
                    .show()
                return
            }
            wifiPass = etWifiPwd?.text.toString()

            preference.putString(Config.PERFERS_WIFIACCOUNT, wifiAccount) //保存本次输入的WiFi账号
            preference.putString(wifiAccount, wifiPass)
            sendNetWorkWIFI()
        } else if (view.id == R.id.iv_pull_down_wifi_list) {
            showWIFIList()
        } else if (view.id == R.id.btn_success) {
            // 绑定成功，查看设备
            EventBus.getDefault()
                .postSticky(EventTotalThread(Config.METHOD_CLOSE_LEFT_MENU_ADD_DEV_INTER))
            finish()
        } else if (view.id == R.id.tv_net5g_hint) {
            // 网络识别（是否是2.4G网络）帮助

        }
    }


    /**
     * 搜索蓝牙
     */
    @SuppressLint("MissingPermission")
    private fun scan() {
        // 重置蓝牙连接状态
        isConnectBlue = false
        // 初始化扫描回调
        mScanCallback = ScanCallback()
        // 开始搜索蓝牙设备
        ELog.e("blue", "blue start")
        try {
            // 获取默认的蓝牙适配器
            val adapter = BluetoothAdapter.getDefaultAdapter()
            // 获取蓝牙LE扫描器
            scanner = adapter.bluetoothLeScanner
            // 检查蓝牙是否启用及扫描器是否可用
            if (!adapter.isEnabled || scanner == null) {
                // 蓝牙未启用或扫描器不可用时，显示提示对话框
                openNoBlueDialog()
            } else {
                Log.e("blue", "blue start 1")
                // 判断是蓝牙还是热点
                mHandler.sendEmptyMessageDelayed(HANDLER_SEARCH_BLUE_TIME_OUT, 50 * 1000)
                // 在Android M及以上版本，检查位置服务是否启用
                val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
                val locationEnable = LocationManagerCompat.isLocationEnabled(
                    locationManager
                )
                // 如果位置服务未启用，显示提示信息
                if (!locationEnable) {
                    Toast.makeText(this, R.string.main_location_disable_msg, Toast.LENGTH_SHORT)
                        .show()
                    return
                }
                Log.e("blue", "blue start 2")
                // 开始扫描蓝牙设备
                scanner?.startScan(
                    null,
                    ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(),
                    mScanCallback
                )
                // 显示扫描蓝牙设备的进度对话框
                createProgressDialog(this, R.string.scan_bluetooth, true)
            }
        } catch (e: Exception) {
            // 异常处理：记录日志并显示提示对话框
            Log.e("blue", "blue start e" + e.message)
            openNoBlueDialog()
        }
    }


    /**
     * 在没有蓝牙权限时弹出对话框
     * 此函数根据Android版本选择性地处理蓝牙权限请求和蓝牙启用
     */
    @SuppressLint("MissingPermission")
    private fun openNoBlueDialog() {
        // 对Android S及以上版本进行特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // 使用XXPermissions库请求蓝牙权限
            XXPermissions.with(this) //单个权限
                .permission(*Config.PERMISSIONS_BLUE)
                .interceptor(PermissionInterceptor()) //  .unchecked()
                .request { permissions2: List<String?>?, all2: Boolean ->
                    // 如果获得所有请求的权限，则请求用户启用蓝牙
                    if (all2) {
                        val intent =
                            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                        startActivityForResult(intent, REQUEST_ENABLE_BT)
                    } else {
                        // 如果未获得所有权限，则结束当前活动
                        finish()
                    }
                }
        } else {
            // 对于Android S以下版本，直接请求用户启用蓝牙
            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(intent, REQUEST_ENABLE_BT)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (REQUEST_ENABLE_BT == requestCode) {
            if (resultCode == RESULT_CANCELED) {
                finish()
            } else {
                scan()
            }
        }
    }

    inner class ScanCallback : android.bluetooth.le.ScanCallback() {

        override fun onBatchScanResults(results: List<ScanResult>) {
            for (result in results) {
                onLeScan(result)
            }
        }

        override fun onScanResult(callbackType: Int, result: ScanResult) {
            onLeScan(result)
        }

        /**
         * 处理蓝牙扫描结果的回调函数
         *
         * @param scanResult 扫描结果对象，包含设备信息和广告数据
         */
        private fun onLeScan(scanResult: ScanResult) {
            // 忽略权限检查的注解，因为此处假设权限已经处理
            @SuppressLint("MissingPermission") val name = scanResult.device.name

            // 检查设备名称是否非空
            if (StringUtils.isNotEmpty(name)) {
                // 打印调试日志，显示正在扫描的蓝牙设备名称和当前连接状态
                ELog.d(TAG, "正在扫描蓝牙..", name, isConnectBlue)
                if(!name.equals("BLUFI")) {
                    // 如果设备名称以特定前缀开头且当前未连接到蓝牙设备，则尝试连接
                    if (name.startsWith(Config.BLUFI_PREFIX) && !isConnectBlue) {
                        devRole = if (name.equals("BLUFI_WS3")) {
                            BuddyType.TYPE_WIFI_DOOR_WS3
                        } else if (name.equals("BLUFI_WS2")) {
                            BuddyType.TYPE_WIFI_DOOR_WS2
                        } else if (name.equals("BLUFI_WM1")) {
                            BuddyType.TYPE_WIFI_DOOR_VM6
                        } else {
                           1
                        }
                        connectBlufi(scanResult.device)
                    }
                }
            }
        }
    }


    /**
     * 连接蓝牙
     *
     * @param device 要连接的蓝牙设备
     */
    private fun connectBlufi(device: BluetoothDevice) {
        // 停止蓝牙扫描
        stopScan()
        // 如果当前已有蓝牙客户端实例，请求关闭连接并释放资源
        if (mBlufiClient != null) {
            mBlufiClient!!.requestCloseConnection()
            mBlufiClient!!.close()
            mBlufiClient = null
        }
        // 创建新的蓝牙客户端实例
        mBlufiClient = BlufiClient(applicationContext, device)
        // 设置蓝牙Gatt回调
        mBlufiClient!!.setGattCallback(GattCallback())
        // 设置Blufi特定的回调
        mBlufiClient!!.setBlufiCallback(BlufiCallbackMain())
        // 设置Gatt写操作的超时时间
        mBlufiClient!!.setGattWriteTimeout(10000L)
        // 设置是否支持自定义设备角色
        Log.e("blue", "blue start 3 "+devRole!!)
        if(devRole==BuddyType.TYPE_WIFI_DOOR_WS3 || devRole==BuddyType.TYPE_WIFI_DOOR_VM6){
            devRole=32000
        }
        mBlufiClient!!.setSupportCustom(devRole!!)
        // 尝试连接到蓝牙设备
        mBlufiClient!!.connect()
    }


    /**
     * 获取WIFI列表
     */
    private fun sendGetWIFI() {
        try {
            val jsonObject = JSONObject()
            jsonObject.put("method", "wifilist")
            val sendMsg = jsonObject.toString()
            ELog.d(TAG, "蓝牙发送数据", sendMsg)
            mBlufiClient!!.postCustomData(sendMsg.toByteArray())
            mHandler.sendEmptyMessageAtTime(HANDLER_GET_WIFI_TIME_OUT, 15000)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    var main_ip = ""
    var sub_ip = ""

    fun getIpDetails() {
        Executors.newSingleThreadExecutor().submit {
            try {
                val mIpStr = preference.getMainUrl()!!.split(":".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray()[0]
                val subIpStr =
                    preference.getSubUrl()!!.split(":".toRegex())
                        .dropLastWhile { it.isEmpty() }
                        .toTypedArray()[0]
                Log.e(TAG,".............."+preference.getMainUrl())
                main_ip = getInetAddress(mIpStr)!!
                sub_ip = getInetAddress(subIpStr)!!
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 解析域名获取IP数组
     *
     * @param host
     * @return
     */
    fun getInetAddress(host: String?): String? {
        var IPAddress = ""
        var ReturnStr1: InetAddress? = null
        try {
            ReturnStr1 = InetAddress.getByName(host)
            IPAddress = ReturnStr1.hostAddress
        } catch (e: UnknownHostException) {
            e.printStackTrace()
            return IPAddress
        }
        return IPAddress
    }

    /**
     * 发送配网信息
     */
    private fun sendNetWorkWIFI() {
        // 创建进度对话框，提示用户正在发送WiFi信息
        createProgressDialog(this, R.string.send_wifi_info, true)
        // 发送WiFi信息超时设置，30秒后如果没有响应则认为发送失败
        mHandler.sendEmptyMessageDelayed(HANDLER_SEND_WIFI_TIME_OUT, 30 * 1000)
        // 创建JSON对象用于封装配网信息
        val jsonObject = JSONObject()
        try {
            // 将WiFi账号、密码、用户名、主IP、子IP等信息封装到JSON对象中
            jsonObject.put("ssid", wifiAccount)
            jsonObject.put("pwd", wifiPass)
            // 将用户名等信息封装到JSON对象中
            jsonObject.put("user_name", userName)
            // 将主IP和子IP等信息封装到JSON对象中，可不传递，建议传递，部分地区设备可能无法解析DNS
            jsonObject.put("main_ip", main_ip)
            jsonObject.put("sub_ip", sub_ip)
            // 设置设备是否在国外，国外传1，国内传0
            jsonObject.put("is_overseas",0)
            jsonObject.put("server_type",1)
            // 针对对接用户，设置第三方品牌ID，需要向移康申请
            jsonObject.put("thirdPartyId", Config.THIRD_BRAND_ID)
            // 设置设备的时间区
            jsonObject.put("time_zone", equesMytool!!.getTimeZoneDSTHour())
            //获取当前服务器分发的ID,用于防止设备分发到别的服务器，出现和APP不一致的情况
            val colony_id = preference.getInt2("colony_id", -1)
            if (colony_id != -1) {
                jsonObject.put("colony", colony_id)
                //当集合到6以后，需要传colony_server 用于自定义服务器分发
                if (colony_id > 5) {
                    val colony_server = preference.getString("colony_server", "")
                    jsonObject.put("colony_addr", colony_server)
                }
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        // 将JSON对象转换为字符串，准备发送
        val sendMsg = jsonObject.toString()
        // 打印日志，记录发送的数据
        ELog.d(TAG, "蓝牙发送数据", sendMsg)
        // 通过蓝牙发送配网信息
        mBlufiClient!!.postCustomData(sendMsg.toByteArray())
    }


    /**
     * 蓝牙连接模块 乐鑫
     */
    inner class BlufiCallbackMain : BlufiCallback() {
        @SuppressLint("MissingPermission")
        override fun onGattPrepared(
            client: BlufiClient, gatt: BluetoothGatt, service: BluetoothGattService,
            writeChar: BluetoothGattCharacteristic, notifyChar: BluetoothGattCharacteristic
        ) {
            if (service == null) {
                ELog.w("Discover service failed")
                gatt.disconnect()
                return
            }
            if (writeChar == null) {
                ELog.w("Get write characteristic failed")
                gatt.disconnect()
                return
            }
            if (notifyChar == null) {
                ELog.w("Get notification characteristic failed")
                gatt.disconnect()
                return
            }
            val mtu = 512
            val requestMtu = gatt.requestMtu(mtu)
            if (!requestMtu) {
                ELog.w("Request mtu failed")
            }
            mHandler.postDelayed(Runnable { sendGetWIFI() }, 1000)
            ELog.d(TAG, "蓝牙 onGattPrepared 发送数据")


        }

        override fun onNegotiateSecurityResult(client: BlufiClient, status: Int) {
            ELog.d(TAG, "蓝牙 onNegotiateSecurityResult")
        }

        override fun onPostConfigureParams(client: BlufiClient, status: Int) {
            ELog.d(TAG, "蓝牙 onPostConfigureParams")
        }

        override fun onDeviceStatusResponse(
            client: BlufiClient,
            status: Int,
            response: BlufiStatusResponse
        ) {
            ELog.d(TAG, "蓝牙 onDeviceStatusResponse")
        }

        override fun onDeviceScanResult(
            client: BlufiClient,
            status: Int,
            results: List<BlufiScanResult>
        ) {
            ELog.d(TAG, "蓝牙 onDeviceScanResult")
        }

        override fun onDeviceVersionResponse(
            client: BlufiClient,
            status: Int,
            response: BlufiVersionResponse
        ) {
            ELog.d(TAG, "蓝牙 onDeviceVersionResponse")
        }

        override fun onPostCustomDataResult(client: BlufiClient, status: Int, data: ByteArray) {
            val dataStr = String(data)
            val format = "Post data %s %s"
            ELog.d(TAG, "蓝牙发送数据", dataStr)
        }

        /**
         * 当接收到自定义数据时调用
         *
         * @param client Blufi客户端实例，用于与蓝牙设备进行通信
         * @param status 数据接收状态，表示接收操作的结果
         * @param data 接收到的数据，以字节数组形式表示
         */
        override fun onReceiveCustomData(client: BlufiClient, status: Int, data: ByteArray) {
            // 将接收到的字节数组转换为字符串
            val dataStr = String(data)
            // 日志输出接收到的蓝牙数据
            ELog.d("收到蓝牙数据：", dataStr)

            // 检查接收到的数据是否包含特定关键字，以确定如何处理数据
            if (dataStr.contains("eques_wifi_config")) {
                // 如果数据包含关键字，解析设备消息
                parseDeviceMsg(dataStr)
            } else {
                // 移除获取WiFi配置的超时消息
                mHandler.removeMessages(HANDLER_GET_WIFI_TIME_OUT)

                // 根据数据内容执行相应的操作
                when (dataStr) {
                    "start" -> {
                        // 当数据为"start"时，准备开始接收后续数据
                        isReceiveData = true
                        stringBuilder = StringBuilder()
                    }

                    "end" -> {
                        // 当数据为"end"时，停止接收数据，并处理接收到的信息
                        isReceiveData = false
                        // TODO 进入网络选择界面
                        val wifiListStr: String = stringBuilder.toString()
                        // 解析网络信息
                        parseNetWorkInfo(wifiListStr)
                        // 移除搜索蓝牙设备的超时消息
                        mHandler.removeMessages(HANDLER_SEARCH_BLUE_TIME_OUT)
                        // 更新绑定步骤类型为已获取WiFi信息
                        bindStepType = BIND_HAS_GET_WIFI
                        // 显示当前步骤视图
                        showStepView()
                        // 停止进度对话框
                        stopProgressDialog()
                        // 显示WiFi列表
                        showWIFIList()
                    }

                    else -> {
                        // 如果正在接收数据，将当前数据追加到字符串构建器中
                        if (isReceiveData) {
                            stringBuilder.append(dataStr)
                        }
                    }
                }
            }
        }

        override fun onError(client: BlufiClient, errCode: Int) {
            ELog.d(TAG, "蓝牙 onError", errCode)
        }
    }

    private fun parseNetWorkInfo(msg: String) {
        if (StringUtils.isNotEmpty(msg)) {
            try {
                val jsonObject = JSONObject(msg)
                val list = jsonObject.getString("list")
                wifiListBean = JSON.parseArray<WifiListBean>(list, WifiListBean::class.java)
            } catch (e: java.lang.Exception) {
                ELog.d(TAG, "Exception:", e.message)
                e.printStackTrace()
            }
        }
    }

    /**
     * 解析设备消息
     * 此函数用于处理设备返回的消息，根据消息内容更新UI和状态
     *
     * @param msg 设备返回的消息字符串，包含WiFi配置结果
     */
    private fun parseDeviceMsg(msg: String) {
        // 停止显示进度对话框
        stopProgressDialog()
        // 取消发送WiFi超时消息
        mHandler.removeMessages(HANDLER_SEND_WIFI_TIME_OUT)
        // 解析消息字符串为WifiConfigResult对象
        var wifiListBean = JSON.parseObject(msg, WifiConfigResult::class.java)
        // 检查解析后的对象是否为空
        if (!ObjIsEmptyUtils.isEmpty(wifiListBean)) {
            // 获取WiFi配置状态码
            val code = wifiListBean.eques_wifi_config.status
            // 初始化设置WiFi成功标志为false
            isSetWifiSuccess = false
            // 初始化提示消息为空字符串
            var remindMsg = ""
            // 获取WiFi配置的描述信息
            val describe = wifiListBean.eques_wifi_config.describe
            // 根据状态码执行相应的操作
            when (code) {
                0 -> {
                    // 如果配置成功，更新绑定步骤类型为成功，并显示步骤视图
                    bindStepType = BIND_DEVICE_SUCCESS
                    showStepView()
                    // 设置WiFi成功标志为true
                    isSetWifiSuccess = true
                }

                1 -> remindMsg = getString(R.string.bind_wifi_fail_hint1)
                2 -> remindMsg = getString(R.string.bind_wifi_fail_hint2)
                3 -> remindMsg = getString(R.string.bind_wifi_fail_hint3)
                4 -> remindMsg = getString(R.string.bind_wifi_fail_hint4)
                7 -> remindMsg = getString(R.string.bind_wifi_fail_hint7)
                else -> remindMsg = ""
            }
            // 如果配置不成功，显示提示消息
            if (code != 0) {
                //上传绑定失败结果
                showToast(remindMsg)
            }
        }
    }

    /**
     * 显示WIFI列表 热点蓝牙公用
     */
    fun showWIFIList() {
        if (wifiListBean != null) {
            PopUtils(this@BindDevActivity).setView(cst_layout).setWifiList(wifiListBean)
                .initShowPop(PopUtils.WIFI_LIST_ANIMAL)
        }
    }

    /**
     * 设置当前WIFI名称
     *
     * @param wifiName
     */
    fun setWifiName(wifiName: String?) {
        etWifiAccount!!.setText(wifiName)
    }


    /**
     * mBlufiClient call onCharacteristicWrite and onCharacteristicChanged is required
     */
    inner class GattCallback : BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            val devAddr = gatt.device.address
            ELog.d(
                String.format(
                    Locale.ENGLISH,
                    "blueTooth onConnectionStateChange addr=%s, status=%d, newState=%d",
                    devAddr,
                    status,
                    newState
                )
            )
            ELog.d(TAG, " 蓝牙 status......$status" + ".....$newState")
            if (status == BluetoothGatt.GATT_SUCCESS) {
                when (newState) {
                    BluetoothProfile.STATE_CONNECTED -> {
                        isConnectBlue = true
                        stopScan()
                    }

                    BluetoothProfile.STATE_DISCONNECTED -> {
                        ELog.d(TAG, "蓝牙连接失败")
                        gatt.close()
                    }
                }
            } else {
                gatt.close()
            }
        }

        override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
            ELog.d(
                TAG,
                String.format(
                    Locale.ENGLISH,
                    "blueTooth onMtuChanged status=%d, mtu=%d",
                    status,
                    mtu
                )
            )
            if (status == BluetoothGatt.GATT_SUCCESS) {
            } else {
                mBlufiClient!!.setPostPackageLengthLimit(50)
            }
        }

        @SuppressLint("MissingPermission")
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            if (status != BluetoothGatt.GATT_SUCCESS) {
                gatt.disconnect()
            }
            ELog.d(
                String.format(
                    Locale.ENGLISH,
                    "blueTooth onServicesDiscovered status=%d",
                    status
                )
            )
        }

        override fun onDescriptorWrite(
            gatt: BluetoothGatt,
            descriptor: BluetoothGattDescriptor,
            status: Int
        ) {
            ELog.d(
                String.format(
                    Locale.ENGLISH,
                    "blueTooth onDescriptorWrite status=%d",
                    status
                )
            )
        }

        @SuppressLint("MissingPermission")
        override fun onCharacteristicWrite(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic,
            status: Int
        ) {
            if (status != BluetoothGatt.GATT_SUCCESS) {
                gatt.disconnect()
            }
        }

        override fun onCharacteristicRead(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic,
            status: Int
        ) {
            super.onCharacteristicRead(gatt, characteristic, status)
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 收到的数据
                val receiveByte = characteristic.value
                val key = String(receiveByte)
                ELog.d(TAG, "接收数据成功-->$key")
            } else {
                ELog.d(TAG, "接收数据失败-->$status")
            }
        }
    }

    private fun showStepView() {
        if (bindStepType == BIND_HAS_GET_WIFI) {
            tvMainTitleHint!!.text = getString(R.string.setting_wifi)
            constraintGlide?.visibility = View.GONE
            linAddWifi?.visibility = View.VISIBLE
        } else if (bindStepType == BIND_DEVICE_SUCCESS) {
            tvMainTitleHint!!.text = getString(R.string.add_animal_success)
            relBindSuccess?.visibility = View.VISIBLE
            linAddWifi?.visibility = View.GONE
        }

    }

    /**
     * 停止扫描
     */
    @SuppressLint("MissingPermission")
    fun stopScan() {
        val adapter = BluetoothAdapter.getDefaultAdapter()
        val scanner = adapter.bluetoothLeScanner
        scanner?.stopScan(mScanCallback)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshEvent(event: EventTotalThread) {
        when (event.refresh) {
            Config.METHOD_METHOD_FINISH_ACTIVITY -> finish()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this@BindDevActivity)
        if (mBlufiClient != null) {
            mBlufiClient!!.requestCloseConnection()
            mBlufiClient!!.close()
            mBlufiClient = null
        }
        stopScan()
    }


}